﻿using System;
using System.Web.Hosting;

namespace HashFoo.Rest.Server
{
    /// <summary>
    /// Makes ASP and IIS aware that there is a job running on a background thread.
    /// </summary>
    /// <remarks>
    /// See: http://haacked.com/archive/2011/10/16/the-dangers-of-implementing-recurring-background-tasks-in-asp-net.aspx for details.
    /// </remarks>
    public class AspJobHost<TJob> : IRegisteredObject
    {
        readonly TJob _job;
        readonly Action<TJob> _shutdownInvoker;

        /// <summary>
        /// Create a job that can be hosted in an ASP worker process.
        /// </summary>
        /// <param name="job"></param>
        /// <param name="shutdownInvoker"></param>
        public AspJobHost(
            TJob job,
            Action<TJob> shutdownInvoker)
        {
            _job = job;
            _shutdownInvoker = shutdownInvoker;

            HostingEnvironment.RegisterObject(this);
        }

        /// <summary>
        /// The job that is being hosted.
        /// </summary>
        public TJob Job
        {
            get { return _job; }
        }

        /// <summary>
        /// Requests a registered object to unregister.
        /// </summary>
        /// <param name="immediate">true to indicate the registered object should unregister from the hosting environment before returning; otherwise, false.</param>
        public void Stop(bool immediate)
        {
            _shutdownInvoker(Job);

            HostingEnvironment.UnregisterObject(this);
        }
    }
}